<template>
  <div class="relative w-full h-full">
    <PageHeader :title="$t('point_setting.index.积分管理')" />
    <el-form
      :model="formData"
      label-width="200px"
      ref="formRef"
      :rules="rules"
      v-loading="loading"
    >
      <el-form-item :label="$t('point_setting.index.购买商品赠送积分')" prop="pointGiveRate">
        <div>
          <el-input-number
            v-model="formData.pointGiveRate"
            style="width: 300px"
            :step="1"
            controls-position="right"
            :min="0"
          />
          <div class="color-666666 fs-12">
            {{ $t('point_setting.index.设置购买商品时获得的积分比例如设置为10则表示消费10元赠送1积分0为购物不赠送积分') }}
          </div>
        </div>
      </el-form-item>

      <el-form-item :label="$t('point_setting.index.单笔订单最大积分赠送数')" prop="pointGiveTotalLimit">
        <div>
          <el-input-number
            v-model="formData.pointGiveTotalLimit"
            style="width: 300px"
            :step="1"
            controls-position="right"
            :min="0"
          />
          <div class="color-666666 fs-12">
            {{ $t('point_setting.index.限制购买商品时单笔订单最多可获得积分数量0为不限制') }}
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">{{ $t('point_setting.index.保存') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t: $t } = useI18n();

const formData = ref({
  pointGiveRate: "",
  pointGiveTotalLimit: "",
});
const formRef = ref(null);
const rules = ref({
  pointGiveRate: [{ required: true, message: $t('point_setting.index.请输入购买商品赠送积分') }],
  pointGiveTotalLimit: [
    { required: true, message: $t('point_setting.index.请输入单笔订单最大积分赠送数') },
  ],
});
const loading = ref(false);

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      Api.saveConfig({
        ...formData.value,
      }).then((res) => {
        if (res.status === 200) {
          ElMessage.success($t('point_setting.index.保存成功'));
          getConfig();
        }
      });
    }
  });
};

const getConfig = () => {
  loading.value = true;
  Api.getConfig()
    .then((res) => {
      if (res.status === 200) {
        formData.value.pointGiveRate = res.data?.pointGiveRate;
        formData.value.pointGiveTotalLimit = res.data?.pointGiveTotalLimit;
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  getConfig();
});
</script>

<style lang="scss" scoped></style>
